package main

import (
	"os"
	"os/signal"
	"sync"
	"time"

	"git.oschina.net/antlinker/antevent/server/antoauth"

	"github.com/antlinker/alog/log"

	"git.oschina.net/antlinker/antevent/server/evtlog"

	"github.com/antlinker/alog"
	"github.com/antlinker/sdk/asapi"

	"git.oschina.net/antlinker/antevent/prodapi"

	"context"

	"gopkg.in/urfave/cli.v2"
)

func createProd() []cli.Flag {
	return []cli.Flag{
		&cli.BoolFlag{
			Name:    "debug",
			Aliases: []string{"d"},
			Usage:   "是否开启日志，默认关闭",
		},
		&cli.StringFlag{
			Name:    "servername",
			Aliases: []string{"sn"},
			Value:   "anteventprod",
			Usage:   "事件引擎服务，生产者ａｐｉ测试工具",
		},
		&cli.StringFlag{
			Name:    "evthost",
			Aliases: []string{"eh"},
			Value:   "127.0.0.1:8080",
			Usage:   "事件引擎服务主机ip:port",
		},
		&cli.StringFlag{
			Name:    "scheme",
			Aliases: []string{"s"},
			Value:   "http",
			Usage:   "事件引擎服务协议 http或https",
		},
		&cli.StringFlag{
			Name:    "authurl",
			Aliases: []string{"au"},
			Value:   "http://192.168.1.202:8090",
			Usage:   "认证中心,必填",
		},
		&cli.StringFlag{
			Name:    "authcid",
			Aliases: []string{"aci"},
			Value:   "595d9a541d41c80523b4cb5c",
			Usage:   "认证中心,客户端id",
		},
		&cli.StringFlag{
			Name:    "authsecret",
			Aliases: []string{"as"},
			Value:   "69b99ef80c23aab002791af6cb38dcdbf2e72e9e",
			Usage:   "认证中心密钥",
		},
		&cli.StringFlag{
			Name:    "authidentify",
			Aliases: []string{"ai"},
			Value:   "ANT",
			Usage:   "服务标识",
		},
		&cli.StringFlag{
			Name:    "etype",
			Aliases: []string{"e"},
			Value:   "",
			Usage:   "事件类型",
		},
		&cli.StringFlag{
			Name:    "action",
			Aliases: []string{"a"},
			Value:   "",
			Usage:   "事件行为",
		},
		&cli.StringFlag{
			Name:    "param",
			Aliases: []string{"p"},
			Value:   "",
			Usage:   "事件参数",
		},
		&cli.IntFlag{
			Name:    "goruncnt",
			Aliases: []string{"gn"},
			Value:   1,
			Usage:   "发送线程数量",
		},
		&cli.IntFlag{
			Name:    "sendcnt",
			Aliases: []string{"n"},
			Value:   1,
			Usage:   "每个线程发送数量",
		},
		&cli.IntFlag{
			Name:    "sendspace",
			Aliases: []string{"ss"},
			Value:   1000,
			Usage:   "每个线程发送间隔时间单位毫秒",
		},
		&cli.StringFlag{
			Name:    "pprof",
			Aliases: []string{"pp"},
			Value:   "",
			Usage:   "启动pprof分析程序,默认不启动，可以设置:9090,指定一个监听ip端口通过http访问",
		},

		&cli.StringFlag{
			Name:    "jwtsignedkey",
			Aliases: []string{"jk"},
			Value:   "antjwt2017",
			Usage:   "jwt　key",
		},
	}
}
func initProd(c *cli.Context) error {
	debug := c.Bool("debug")
	if debug {
		alog.GALog.SetLogLevel(log.DEBUG)
	} else {
		alog.GALog.SetLogLevel(log.INFO)
	}
	pprof(c)
	etype := c.String("etype")
	action := c.String("action")
	param := c.String("param")
	servername := c.String("servername")
	host := c.String("evthost")
	scheme := c.String("scheme")
	url := c.String("authurl")
	authcid := c.String("authcid")
	authsecret := c.String("authsecret")
	authidentify := c.String("authidentify")

	sendspace := c.Int64("sendspace")
	ss := time.Duration(sendspace) * time.Millisecond
	goruncnt := c.Int("goruncnt")
	sendcnt := c.Int("sendcnt")
	jwtSignedKey := c.String("jwtsignedkey")
	opt := prodapi.Options{
		Name:   servername,
		Host:   host,
		Scheme: scheme,
		AuthCfg: antoauth.SignerOption{
			AuthCfg: &asapi.Config{
				ASURL:           url,
				ClientID:        authcid,
				ClientSecret:    authsecret,
				ServiceIdentify: authidentify,
			},

			JWTSignedKey: jwtSignedKey,
		},
	}

	cli := prodapi.NewClient(opt)
	wait := sync.WaitGroup{}
	start := time.Now()
	for i := 0; i < goruncnt; i++ {
		wait.Add(1)
		go func(i int) {
			defer wait.Done()
			for j := 0; j < sendcnt; j++ {
				eid, err := cli.Send(context.Background(), etype, action, param)
				if err != nil {

					evtlog.Debug("发送事件失败:%v\n", err)

					continue
				}
				evtlog.Debug("发送事件成功:%v\n", eid)
				select {
				case <-stop:
					return
				case <-time.After(ss):

				}
			}
		}(i)
	}
	regSigin()
	wait.Wait()
	t := time.Since(start)
	total := goruncnt * sendcnt
	evtlog.Info("发送%d个事件经历%v,平均每秒发送%f个事件 \n", total, t, float64(total)/t.Seconds())
	return nil
}

var (
	stop = make(chan struct{}, 0)
)

func regSigin() {

	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, os.Interrupt, os.Kill)
	<-sigc
	close(stop)
	go func() {
		signal.Notify(sigc, os.Interrupt, os.Kill)
		<-sigc
		evtlog.Info("在此收到了退出程序信号，强制退出")
		os.Exit(9)
	}()

}
